#!/bin/bash

set -eu -o pipefail

helpexit() {
  echo "$0 start|stop|killwineserver|wineconfig"
  exit 1
}

test -n "${1:-}" || helpexit
action=$1

WINECONFIG=$HOME/.local/share/paimon-launcher/wineconfig.sh
if [ ! -e "$WINECONFIG" ]; then
  cat > "$WINECONFIG" <<-EOF
	# config file for wine

	echo "Using $WINECONFIG, feel free to adjust it for your needs"

	# don't spam to console
	export WINEDEBUG=-all

	# use eSync - may improve frame rate with wine-stating signifacantly
	export WINEESYNC=1

	# uncomment to draw FPS in game
	# export DXVK_HUD=fps

	# setup path to wine bin dir here, leave empty to autodetect winehq installation
	# examples:
	# WINEPATH=/opt/wine-devel/bin
	# WINEPATH="\$HOME/.steam/steam/steamapps/common/Proton - Experimental"
	WINEPATH=

	# game launch command
	#WINESTARTCMD="proton cmd /c launcher.bat"
	WINESTARTCMD="wine cmd /c launcher.bat"

	# alternative command line with explorer desktop
	#WINESTARTCMD="wine explorer /desktop=anyname,1920x1080 cmd /c launcher.bat"


	# command to stop game
	WINESTOPCMD="killall *.exe"


	# kill wine server command
	KILLWINESERVER="wineserver -k"
EOF
fi

if [ "$action" = "wineconfig" ]; then
  xdg-open "$WINECONFIG"
  exit 0
fi


. "$WINECONFIG"

# prefer wine-staging, it works best ATM

if [ -z "${WINEPATH:-}" ]; then
  if [ -e /opt/wine-staging/bin/wine ]; then
    export PATH=/opt/wine-staging/bin:$PATH
  else
    echo "For improved frame rate wine-stating 6.7+ is recommended."

    if [ -e /opt/wine-devel/bin/wine ]; then
      export PATH=/opt/wine-devel/bin:$PATH
    else
      echo "Using default wine installation..."
    fi
  fi
fi

case $action in
  start)
    exec ${WINESTARTCMD:-wine cmd /c launcher.bat}
    ;;

  stop)
    # no better way to do this?
    ${WINESTOPCMD:-killall *.exe}
    ;;

  killwineserver)
    ${KILLWINESERVER:-wineserver -k}
    ;;

  *)
    helpexit
    ;;
esac
